//获取token
var token = CoreUtil.getData("access_token");
//地址栏转义token中的#号
var tokenQuery = token.replace("#", "%23");
var tableIns1;
var table = layui.table;
var form = layui.form;
var layer = layui.layer;
var $ = jQuery = layui.jquery;
var laydate = layui.laydate;
var upload = layui.upload;
var layedit = layui.layedit;
var storeAlbum = [];
var selectNode = null;

layui.config({
    base: '/'
}).extend({
    tinymce: 'layui_exts/tinymce/tinymce'
}).use(['tinymce', 'table', 'layer', 'laydate', 'layedit', 'upload',], function () {

    //加载table
    tableIns1 = table.render({
        elem: '#showTable'
        , contentType: 'application/json'
        , headers: {"authorization": token}
        , page: true //开启分页
        , url: '/sysGoods/listByPage' //数据接口
        , method: 'POST'
        , parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": CoreUtil.isEmpty(res.data) ? 0 : res.data.total, //解析数据长度
                "data": CoreUtil.isEmpty(res.data) ? null : res.data.records //解析数据列表
            }
        }
        , cols: [
            [
                {type: 'checkbox', fixed: 'left'},
                {field: 'id', title: '', sort: true},
                {field: 'storeId', title: '', sort: true},
                {field: 'goodsName', title: '商品名称', sort: true},
                {field: 'money', title: '商品价格。单位分', sort: true},
                {field: 'description', title: '简介', sort: true},
                {field: 'coverImg', title: '封面图片', sort: true},
                {field: 'checkCount', title: '点击数', sort: true},
                {field: 'type', title: '', sort: true},
                {field: 'content', title: '', sort: true},
                {field: 'createTime', title: '', sort: true},
                {field: 'updateTime', title: '', sort: true},
                {width: 120, toolbar: "#tool", title: '操作'}
            ]
        ]
        , toolbar: '#toolbar'
    });


    //表头工具
    table.on('toolbar(showTable)', function (obj) {
        switch (obj.event) {
            case 'batchDeleted':
                var checkStatus = table.checkStatus(obj.config.id);
                var data = checkStatus.data;
                if (data.length == 0) {
                    layer.msg("请选择要批量删除的列");
                } else {
                    var ids = [];
                    $(data).each(function (index, item) {
                        ids.push(item.id);
                    });
                    tipDialog(ids);
                }
                break;
            case 'add':
                $(".table_div").hide();
                $(".operation").show();
                $(".title").html("新增");
                $(".operation input[name=id]").val("");
                $(".operation input[name=coverImg]").val("");
                $(".operation input[name=storeId]").val("");

                $(".operation input[name=goodsName]").val("");
                $(".operation input[name=money]").val("");
                $(".operation input[name=description]").val("");
                $(".operation input[name=checkCount]").val("");
                $(".operation input[name=type]").val("");
                $(".operation input[name=content]").val("");
                $(".operation input[name=createTime]").val("");
                $(".operation input[name=updateTime]").val("");
                $('#coverImg').attr('src', '/images/商品发布-点击上传icon.png');
                tinymce.get('#content').setContent('');
                // var content = tinymce.get('#edit').getContent();


                break;
        }
        ;
    });
    //列操作
    table.on('tool(showTable)', function (obj) {
        var data = obj.data;
        switch (obj.event) {
            case 'del':
                var ids = [];
                ids.push(data.id);
                tipDialog(ids);
                break;
            case 'edit':
                $(".table_div").hide();
                $(".operation").show();
                $(".title").html("编辑");
                $(".operation input[name=id]").val(data.id);
                $(".operation input[name=storeId]").val(data.storeId);
                $(".operation input[name=goodsName]").val(data.goodsName);
                $(".operation input[name=money]").val(data.money);
                $(".operation input[name=description]").val(data.description);
                $(".operation input[name=coverImg]").val(data.coverImg);
                $(".operation input[name=checkCount]").val(data.checkCount);
                $(".operation input[name=type]").val(data.type);
                $(".operation input[name=content]").val(data.content);
                $(".operation input[name=createTime]").val(data.createTime);
                $(".operation input[name=updateTime]").val(data.updateTime);

                //
                $('#coverImg').attr('src', imgUrlStr(data.img));

                /// 获取typeMame



                break;
        }
    });
    var init_content = function () {
        var content = tinymce.get('#edit').setContent(data.content);
    }

    //导出
    $('#export').on('click', function () {
        //原先分页limit
        var exportParams = {
            limit: 10000,
            key: $("#key").val()
        };
        CoreUtil.sendPost("/sysGoods/listByPage", exportParams, function (res) {
            //初始化渲染数据
            if (res.data != null && res.data.records != null) {
                table.exportFile(tableIns1.config.id, res.data.records, 'xls');
            }
        });
    });

    //删除
    var tipDialog = function (ids) {
        layer.open({
            content: "确定要删除么?",
            yes: function (index, layero) {
                layer.close(index); //如果设定了yes回调，需进行手工关闭
                CoreUtil.sendDelete("/sysGoods/delete", ids, function (res) {
                    layer.msg(res.msg, {time: 1000}, function () {
                        search();
                    });
                });
            }
        });
    };

    //返回
    $("#btn_cancel").click(function () {
        $(".table_div").show();
        $(".operation").hide();
        return false;
    });

    //监听保存
    form.on('submit(submit)', function (data) {
        data.field.content = tinymce.get('#content').getContent();
        data.field.goodsAlbum = storeAlbum;
        if (data.field.goodsName === undefined || data.field.goodsName === null || data.field.goodsName === "") {
            layer.error("商品名称不能为空！");
            return false;
        }
        if (data.field.coverImg === undefined || data.field.coverImg === null || data.field.coverImg === "") {
            layer.error("未选择封面图片！");
            return false;
        }
        if (data.field.money === undefined || data.field.money === null || data.field.money === "") {
            layer.error("商品价格不能为空！");
            return false;
        }
        if (data.field.type === undefined || data.field.type === null || data.field.type === "") {
            layer.error("未选择商品类型！");
            return false;
        }
        if (data.field.content === undefined || data.field.content === null || data.field.content === "") {
            layer.error("商品描述不能为空！");
            return false;
        }
        if (data.field.id === undefined || data.field.id === null || data.field.id === "") {
            CoreUtil.sendPost("/sysGoods/add", data.field, function (res) {
                $(".table_div").show();
                $(".operation").hide();
                search();
            });
        } else {
            CoreUtil.sendPut("/sysGoods/update", data.field, function (res) {
                $(".table_div").show();
                $(".operation").hide();
                search();
            });
        }
        return false;
    });
    // 图片封面上传
    var coverImgFiles;
    var loadIndex;
    var coverImg = upload.render({
        elem: '#coverImg'
        , url: '/sysFile/uploadImg' //改成您自己的上传接口
        , headers: {"authorization": token}
        , acceptMime: 'image/*'
        , size: 1024        //  最大允许上传的文件大小  单位 KB
        , choose: function (obj) {
            coverImgFiles = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            obj.preview(function (index, file, reslut) {
                // width="300" height="140"
                $('#coverImg').attr('width', '300');
                $('#coverImg').attr('height', '140');
                $('#coverImg').attr('src', reslut);
            })
        }
        , before: function () {
            // 提交前
            loadIndex = top.layer.load(0, {shade: [0.8, '#393D49']});
        }
        , done: function (res) {
            // 上传完毕
            if (res.code == 0) {
                var data = res.data;
                $(".operation input[name=coverImg]").val(data.url);

                coverImgUploadError(false);
            } else {
                //演示失败状态，并实现重传
                coverImgUploadError(true);
            }
        }
        , error: function (index, upload) {
            coverImgUploadError(true);
        }
    });

    // 商品相册上传
    storeAlbum;
    var coverImgUploadError = function (falg) {
        var demoText = $('#coverImg-msg');
        if (falg) {
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                coverImg.upload();
            });
        } else {
            demoText.html('');
        }
        top.layer.close(loadIndex);
    }

    /// 相册图片上传
    var maxAlbumNumber = 6;
    // 添加图片到相册数组
    var addAlbumImg = function (imgId) {
        // 图片数量超过6张不添加
        if (storeAlbum.length < maxAlbumNumber) {
            storeAlbum.push(imgId);
            albumLoad();
        } else {
            layer.error("图片大于6张");
        }
    }

    // 相册显示
    var albumShow = function () {
        $('.albumBox').html('');    // 清空
        for (var i = 0; i < storeAlbum.length; i++) {
            var domHtml = '' +
                '<div class="layui-row albumImgBox" lay-event="' + storeAlbum[i] + '" style="background-image: url(' + imgUrlStr(storeAlbum[i]) + ');">' +
                '	<div class="layui-col-xs4 mode mode-left-img layui-icon layui-icon-left" lay-event="left">' +
                '	</div>' +
                '	<div class="layui-col-xs4" style="height: 100%;" >' +
                '		<div class="mode mode-chakan-img iconfont icon-chakan" style="height: 50% !important;" lay-event="chakan"></div>' +
                '		<div class="mode mode-delete-img layui-icon layui-icon-delete" style="height: 50% !important;" lay-event="delete"></div>' +
                '	</div>' +
                '	<div class="layui-col-xs4 mode mode-right-img layui-icon layui-icon-right" lay-event="right">' +
                '	</div>' +
                '</div>';
            $('.albumBox').append(domHtml);
        }
    }
    var albumImgUploadBut;
    // 上传按钮
    var createUpImgBut = function () {
        // 小于6张图片显示上传按钮
        if (storeAlbum.length < maxAlbumNumber) {
            $('.albumAddBtn').html('<a id="albumImg" class="layui-btn layui-btn-normal" >添加图片</a>');
            albumImgUploadBut = upload.render({
                elem: '#albumImg'
                , url: '/sysFile/uploadImg' //改成您自己的上传接口
                , headers: {"authorization": token}
                , acceptMime: 'image/*'
                , size: 1024        //  最大允许上传的文件大小  单位 KB
                , choose: function (obj) {
                    // 选择文件后
                    loadIndex = top.layer.load(0, {shade: [0.8, '#393D49']});
                    if (storeAlbum.length >= 6) {
                        top.layer.close(loadIndex);
                        return false;
                    }

                }
                , before: function () {
                    // 提交前
                }
                , done: function (res) {
                    // 上传完毕
                    if (res.code == 0) {
                        var data = res.data;
                        addAlbumImg(data.id);
                        top.layer.close(loadIndex);
                    } else {
                        //演示失败状态，并实现重传
                        top.layer.close(loadIndex);
                    }
                }
                , error: function (index, upload) {
                    top.layer.close(loadIndex);
                }
            });
        } else {
            $('.albumAddBtn').html('');
        }
    }

    // 图片按钮
    var hovers = function (elem) {
        $('.mode').on('mouseover mouseout', function () {
            $(this).toggleClass('mode-hover');
            var modeVal = 'mode-img';
            var type = $(this).attr('lay-event');
            if (type == 'left' || type == 'right') {
                $(this).toggleClass(modeVal);
            } else {
                $(this).toggleClass(modeVal + '-' + type);
            }
        });
    }
    // 点击处理图片
    var clickMode = function (elem) {
        $('.mode').on('click', function (obj) {
            var modeType = $(this).attr('lay-event');
            switch (modeType) {
                case 'left':
                    var imgurl = $(this).parent().attr('lay-event');
                    for (var i = 0; i < storeAlbum.length; i++) {
                        // 左边移动 是否第一个
                        if (storeAlbum[i] == imgurl) {
                            if (i == 0) {
                                layer.msg("已经是第一个");
                                break;
                            }
                            storeAlbum[i] = storeAlbum[i - 1]
                            storeAlbum[i - 1] = imgurl;
                            albumLoad();
                            break;
                        }
                    }
                    break;
                case 'right':
                    var imgurl = $(this).parent().attr('lay-event');
                    for (var i = 0; i < storeAlbum.length; i++) {
                        // 左边移动 是否第一个
                        if (storeAlbum[i] == imgurl) {
                            if (i == (storeAlbum.length - 1)) {
                                layer.msg("已经是最后一个");
                                break;
                            }
                            storeAlbum[i] = storeAlbum[i + 1]
                            storeAlbum[i + 1] = imgurl;
                            albumLoad();
                            break;
                        }
                    }
                    break;
                case 'delete':
                    var imgurl = $(this).parent().parent().attr('lay-event');
                    for (var i = 0; i < storeAlbum.length; i++) {
                        if (storeAlbum[i] == imgurl) {
                            layer.msg("移除图片");
                            storeAlbum.splice(i, 1);
                            albumLoad();
                            break;
                        }
                    }
                    break;
                case 'chakan':
                    var imgurl = $(this).parent().parent().attr('lay-event');
                    var img = new Image();
                    img.src = imgUrlStr(imgurl);
                    img.onload = function () {
                        var height = img.height;
                        var width = img.width;
                        var scaleWH = width / height;
                        var bigH = 600;
                        var bigW = scaleWH * bigH;
                        if (bigW > 900) {
                            bigW = 900;
                            bigH = bigW / scaleWH;
                        }
                        layer.open({
                            type: 1,
                            title: false,
                            closeBtn: 1,
                            shadeClose: true,
                            area: [bigW + 'px', bigH + 'px'], //宽高
                            content: '<img width=' + bigW + ' height=' + bigH + ' src="' + img.src + '" />'
                        });
                    }
                    break;
            }
        })
    }

    var albumNumber = function () {
        $('.albumNumber').html('(' + storeAlbum.length + '/' + maxAlbumNumber + ')');
    }

    // 初始化
    // 每次上传完成图片后调用
    var albumLoad = function () {
        albumShow();
        createUpImgBut();
        hovers();
        clickMode();
        albumNumber();
    }
    albumLoad();

    var imgUrlStr = function (imgId) {
        return '/sysFile/imageshow/' + imgId + '?authorization=' + tokenQuery;
    }


    // / 商品详情， 富文本
    // var content = layedit.build('content', {
    //     height: 240
    //     , tool: ['html', 'strong', 'italic', 'underline', 'del', '|', 'left','center','right','face','image','code','help']
    //     , uploadImage: {
    //         url: '/sysContent/picture/upload?authorization=' + tokenQuery //接口url
    //         , type: 'post' //默认post
    //     }
    // });

    var tinymce = layui.tinymce;
    var edit = tinymce.render(
        {
            elem: "#content"
            , height: 800
            , images_upload_url: '/sysContent/picture/upload?authorization=' + tokenQuery
        }
        , function () {
            // 加载完成
        }
    );

    // 选择商品类型





});

//执行查询
function search() {
    //这里以搜索为例
    tableIns1.reload({
        where: { //设定异步数据接口的额外参数，任意设
            key: $("#key").val()
        }
        , page: {
            curr: 1 //重新从第 1 页开始
        }
    });
};